<template>
  <div class="container">
    <el-dialog
       v-drag
       width="54%"
      :title="!dataForm.supplierId ? '新增供应商' : '修改供应商'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <div class="el-dialog-div">
        <el-form :model="dataForm" :inline="true" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
          <el-tabs v-model="activeName" @tab-click="handleClick" type="card">
            <el-tab-pane label="基本信息" name="basic">
              <el-form-item label="供应商类型" prop="supllierType">
                <el-select size="mini" @focus="getDicts('SUPPLY_TYPE')" v-model="dataForm.supllierType" clearable
                  placeholder="请选择">
                  <el-option v-for="item in supllierTypes" :key="item.value" :label="item.label" :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="供应商名称" prop="supplierName">
                <el-input size="mini"  v-model="dataForm.supplierName" placeholder="供应商名称" clearable></el-input>
              </el-form-item>
              <el-form-item label="地址" prop="address">
                <el-input size="mini"  v-model="dataForm.address" placeholder="地址" clearable></el-input>
              </el-form-item>
              <el-form-item label="销售人员" prop="salesman">
                <el-input size="mini"  v-model="dataForm.salesman" placeholder="销售人员" clearable></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="tel">
                <el-input size="mini"  v-model="dataForm.tel" placeholder="电话" clearable></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                <el-input size="mini"  v-model="dataForm.mobile" placeholder="手机" clearable></el-input>
              </el-form-item>
              <el-form-item label="法人代表" prop="corporater">
                <el-input size="mini"  v-model="dataForm.corporater" placeholder="法人代表" clearable></el-input>
              </el-form-item>
              <el-form-item label="营业执照期限" prop="businessTimeLimit">
                <el-date-picker v-model="dataForm.businessTimeLimit" align="right" type="date" size="mini" placeholder="营业执照期限"
                  value-format="yyyy-MM-dd" class="picker-width">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="经营许可证期限" prop="productTimeLimit">
                <el-date-picker v-model="dataForm.productTimeLimit" align="right" type="date" size="mini" placeholder="经营许可证期限"
                  value-format="yyyy-MM-dd" class="picker-width">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="负责人" prop="leader">
                <el-input size="mini"  v-model="dataForm.leader" placeholder="负责人" clearable></el-input>
              </el-form-item>
              <el-form-item label="组织机构代码" prop="organizationCode">
                <el-input size="mini"  v-model="dataForm.organizationCode" placeholder="组织机构代码" clearable></el-input>
              </el-form-item>
              <el-form-item label="组织机构期限" prop="organizationTimeLimit">
                <el-date-picker v-model="dataForm.organizationTimeLimit" align="right" type="date" size="mini" placeholder="经营许可证期限"
                  value-format="yyyy-MM-dd" class="picker-width">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="税务号" prop="taxNumber">
                <el-input size="mini"  v-model="dataForm.taxNumber" placeholder="税务号" clearable></el-input>
              </el-form-item>
              <el-form-item label="下载标识" prop="dataDownloadCode">
                <el-input size="mini"  v-model="dataForm.dataDownloadCode" placeholder="下载标识识" clearable></el-input>
              </el-form-item>
              <el-form-item label="门店共享" prop="isShare">
                <template slot-scope="scope">
                  <el-checkbox size="mini" v-model="dataForm.isShare"  ></el-checkbox>
                </template>
              </el-form-item>
           </el-tab-pane>
           <el-tab-pane label="证件上传" name="image" :inline="false">
               <el-form-item label="营业执照" prop="licenses" :inline="false">
                 <el-upload :action="uploadUrl" :on-preview="handleLicensePreview" :on-remove="handleLicenseRemove"
                   :on-success="handLicenseSuccess" :before-upload="handleLicenseBeforeUpload" :headers="headers"
                   :file-list="dataForm.licenses" :drag="false" list-type="picture" name="file" :data="uploadData">
                   <el-button size="small" type="primary">点击上传</el-button>
                   <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                 </el-upload>
               </el-form-item>
               <br />
               <el-form-item label="产品经营许可证" prop="productCerts" :inline="false">
                 <el-upload :action="uploadUrl" :on-preview="handleProductCertPreview" :on-remove="handleProductCertRemove"
                   :on-success="handProductCertSuccess" :before-upload="handleProductCertBeforeUpload" :headers="headers"
                   :file-list="dataForm.productCerts" :drag="false" list-type="picture" name="file" :data="uploadData">
                   <el-button size="small" type="primary">点击上传</el-button>
                   <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                 </el-upload>
               </el-form-item>
             </el-tab-pane>

             <el-tab-pane label="供应商描述" name="remark">
               <el-form-item label="供应商描述" prop="remark">
                 <quill-editor ref="remark" v-model="dataForm.remark" class="editor" :options="editorOption" />
               </el-form-item>
             </el-tab-pane>
           </el-tabs>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-drag title="图片预览" :visible.sync="imgDialogVisible" width="50%">
      <el-image style="width: 100%;" @close="handCloseImgDialog" :src="previewPath"></el-image>
    </el-dialog>
  </div>
</template>

<script>
   import {getFileName} from '@/utils/myUtil.js'
  export default {
    data () {
      var checkPhone = (rule, value, callback) => {
          const phoneReg = /^(\d{3,4}-)?\d{7,8}$/
          if (!value) {
            return callback(new Error('电话号码不能为空'))
          }
          setTimeout(() => {
            // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
            // 所以我就在前面加了一个+实现隐式转换
              if (phoneReg.test(value)) {
                callback()
              } else {
                callback(new Error('电话号码格式不正确'))
              }
          }, 100)
        }
        // 验证手机号的规则
        var checkMobile = (rules,value,callback) => {
            const regMobile = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
            if (!Number.isInteger(+value)) {
              callback(new Error('请输入数字值'))
            }else if(regMobile.test(value)){
              return callback()
            }
            callback(new Error('请输入合法的手机号'))
        }
        var checkEmail = (rule, value, callback) => {
          const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
          if (!value) {
            return callback(new Error('邮箱不能为空'))
          }
          setTimeout(() => {
            if (mailReg.test(value)) {
              callback()
            } else {
              callback(new Error('请输入正确的邮箱格式'))
            }
          }, 100)
        }
      return {
        visible: false,
        dataForm: {
          supplierId: 0,
          supllierType: '',
          supplierName: '',
          address: '',
          salesman: '',
          tel: '',
          mobile: '',
          corporater: '',
          businessLicense: '',
          businessTimeLimit: '',
          productBusinessLlicense: '',
          productTimeLimit: '',
          leader: '',
          organizationCode: '',
          organizationTimeLimit: '',
          taxNumber: '',
          dataDownloadCode: '',
          isShare: false,
          remark: '',
          licenses: [],
          productCerts: []
        },
        supllierTypes: [],
        editorOption: {
          placeholder: '请输入......'
        },
        previewPath: '',
        imgDialogVisible: false,
        uploadUrl: 'http://localhost:99/api/common/upload',
        headers: {
          Authorization: "Bearer " + this.$cookie.get('token'),
          token: this.$cookie.get('token')
        },
        uploadData: {
          file: ''
        },
        license: {},
        productCert: {},
        activeName: 'basic',
        dataRule: {
          supllierType: [
            { required: true, message: '供应商类型不能为空', trigger: 'blur' }
          ],
          supplierName: [
            { required: true, message: '供应商名称不能为空', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '地址不能为空', trigger: 'blur' }
          ],
          salesman: [
            { required: true, message: '销售人员不能为空', trigger: 'blur' }
          ],
          tel: [
            { required: true, message: '电话不能为空', trigger: 'blur' },
            { validator: checkPhone, trigger:true}
          ],
          mobile: [
            { required: true, message: '手机不能为空', trigger: 'blur' },
            { validator: checkMobile, trigger:true}
          ],
          corporater: [
            { required: true, message: '法人代表不能为空', trigger: 'blur' }
          ],
          businessLicense: [
            { required: true, message: '营业执照不能为空', trigger: 'blur' }
          ],
          businessTimeLimit: [
            { required: true, message: '营业执照期限不能为空', trigger: 'blur' }
          ],
          productBusinessLlicense: [
            { required: true, message: '产品经营许可证不能为空', trigger: 'blur' }
          ],
          productTimeLimit: [
            { required: true, message: '产品经营许可证期限不能为空', trigger: 'blur' }
          ],
          leader: [
            { required: true, message: '负责人不能为空', trigger: 'blur' }
          ],
          organizationCode: [
            { required: true, message: '组织机构代码不能为空', trigger: 'blur' }
          ],
          organizationTimeLimit: [
            { required: true, message: '组织机构期限不能为空', trigger: 'blur' }
          ],
          taxNumber: [
            { required: true, message: '税务号不能为空', trigger: 'blur' }
          ],
        }
      }
    },
    methods: {
      init(supplierId) {
        this.dataForm.supplierId = supplierId
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.supplierId) {
            this.$http({
              url: this.$http.adornUrl(`/product/supplier/info/${this.dataForm.supplierId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {

                let licenses = []
                if (data.productSupplier.businessLicense) {
                  let urls = data.productSupplier.businessLicense.split(",")
                  urls.forEach(url => {
                    let license = {
                      "name": getFileName(url),
                      "url": url
                    }
                    licenses.push(license)
                  })
                }

                let productCerts = []
                if (data.productSupplier.productBusinessLlicense) {
                  let urls = data.productSupplier.productBusinessLlicense.split(",")
                  urls.forEach(url => {
                    let productCert = {
                      "name": getFileName(url),
                      "url": url
                    }
                    productCerts.push(productCert)
                  })
                }
                data.productSupplier.isShare = data.productSupplier.isShare == 1 ? true: false
                this.dataForm = data.productSupplier
                this.dataForm.licenses = licenses
                this.dataForm.productCerts = productCerts
              }
            })
          }
        })
      },
      async getDicts(type) {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': type
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          if (type === 'SUPPLY_TYPE') {
            this.supllierTypes = data.data
          }
        }
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.licenses.length > 0) {
              let urls = []
              this.dataForm.licenses.forEach(item => {
                urls.push(item.url)
              })
              this.dataForm.businessLicense = urls.join(",")
            }else{
              this.dataForm.businessLicense = ''
            }

            if (this.dataForm.productCerts.length > 0) {
              let urls = []
              this.dataForm.productCerts.forEach(item => {
                urls.push(item.url)
              })
              this.dataForm.productBusinessLlicense = urls.join(",")
            }else{
              this.dataForm.productBusinessLlicense = ''
            }

            this.dataForm.isShare = this.dataForm.isShare == true ? 1: 0

            this.$http({
              url: `/product/supplier/${!this.dataForm.supplierId ? 'save' : 'update'}`,
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      //----营业执照-----------------------------
      handleLicensePreview(file, fileList) {
        this.previewPath = file.url
        this.imgDialogVisible = true
      },
      //图片删除
      handleLicenseRemove(file) {
        if(this.dataForm.licenses.length === 1){
          this.dataForm.licenses = []
        }else{
          //找到索引
          const index = this.dataForm.licenses.findIndex(item =>
            item.url === file.url
          )
          //根据索引删除
          this.dataForm.licenses.splice(index, 1)
        }
      },
      //上传之前
      handleLicenseBeforeUpload(file) {
        this.license = {
          "name": file.name,
          "size": file.size,
          "type": file.type,
          "uid": file.uid,
          "status": 1,
        }
      },
      //上传成功
      handLicenseSuccess(response) {
        if (response.code === 0) {
          this.license.url = response.data
          this.dataForm.licenses.push(this.license)
        }
      },
      //--产品经营许可证-----------------------------------
      handleProductCertPreview(file, fileList) {
        this.previewPath = file.url
        this.imgDialogVisible = true
      },
      //图片删除
      handleProductCertRemove(file) {
        if(this.dataForm.productCerts.length === 1){
          this.dataForm.productCerts = []
        }else{
          //找到索引
          const index = this.dataForm.productCerts.findIndex(item =>
            item.url === file.url
          )
          //根据索引删除
          this.dataForm.productCerts.splice(index, 1)
        }

      },
      //上传之前
      handleProductCertBeforeUpload(file) {
        this.productCert = {
          "name": file.name,
          "size": file.size,
          "type": file.type,
          "uid": file.uid,
          "status": 1,
        }
      },
      //上传成功
      handProductCertSuccess(response) {
        if (response.code === 0) {
          this.productCert.url = response.data
          this.dataForm.productCerts.push(this.productCert)
        }
      },
      handCloseImgDialog() {
        this.previewPath = ''
      },
      handleClick() {

      },
      handleCloseSupplierDialog() {
        this.dataForm = {}
        this.productCert = {}
        this.license = {}
      }
    }
  }
</script>
<style lang="less" scoped>
  .el-dialog-div {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 500px!important;
  }
  .el-form--inline .el-form-item__label {
      float: none;
      display: inline-block;
      width: 120px!important;
  }
  .picker-width{
    width: 100%;
  }
</style>
